
package com.ikkong.system.util;

import com.ikkong.common.vo.User;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.jfinal.ext.kit.JsonKit;
import com.ikkong.core.jfinal.ext.shiro.ShiroKit;
import com.ikkong.core.toolbox.kit.DateKit;
import com.ikkong.order.model.MallOrder;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.beetl.sql.core.kit.StringKit;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.*;


public class CommonUtil {
    public static String MES_TYPE = "0";
    public static Integer BUYER_POINT = 0;
    public static Integer SHOPER_POINT = 0;
    private static final Prop prop = PropKit.use("config.properties");
    final static String appkey = prop.get("jgAppkey");
    final static String jgSecret = prop.get("jgSecret");
    private static Date LAST_TOKEN_TIME ;
    private static String WX_TOKEN;
    private static Date LAST_JSAPI_TIME ;
    private static String JSAPI;



    public static void main(String[] args) throws ParseException, WxErrorException {


    }



    public static String testWxMp() throws WxErrorException {
        WxMpService wxMpService = new WxMpServiceImpl();
        String jsapiTicket = wxMpService.getJsapiTicket();
        System.out.println(jsapiTicket);
        return jsapiTicket;

    }


    //发送消息
    public static boolean pushMes(User user,String num,String msg){
        String openid = user.getOpenid();
        String phone = user.getPhone();
        boolean b = false;
            //微信+短信
//            if(StringKit.isNotBlank(phone)){
//                try {
//                    SendMessageUtil.sendByMoban(msg,phone);
//                    b = true;
//                }catch (Exception e){
//                    System.out.println(e);
//                }
//            }

            if(StringKit.isNotBlank(openid)){
                sendOrderMsg(openid,num,msg);
                b = true;
            }




        return  b;
    }


//    查找我的邀请人
    public static Integer getMyParent(Object id){
        User user = Blade.create(User.class).findById(id);
        if(user==null || user.getParent_user() == null){
            return null;
        }else {
            return user.getParent_user();
        }

    }

    public static String hideName(String s){
        int length = s.length();
        if(length>12){
            String before = s.substring(0,4);
            String after = s.substring(length -4);
            s = before + "****" + after;
        }else if(length<=12 && length >6){
            String before = s.substring(0,3);
            String after = s.substring(length -3);
            s = before + "****" + after;
        }else if(length > 2 && length <6){
            String before = s.substring(0,1);
            String after = s.substring(length -1);
            s = before + "****" + after;
        }else {
            s = s.substring(0,1) + "*";
        }
        return s;
    }

    public static String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx86f9f7be6024c5a0&secret=b6a6e9e38433cadfa300f626f304fbd9";
        String s = "";

        if(StringKit.isBlank(WX_TOKEN)){
           s = HttpKit.get(url);
            LAST_TOKEN_TIME = DateKit.getAfterMin(110);//更新token
        }else {
            if(LAST_TOKEN_TIME == null ){
                 s = HttpKit.get(url);
                LAST_TOKEN_TIME = DateKit.getAfterMin(110);//更新token
            }else {
                if(new Date().after(LAST_TOKEN_TIME)){//如果token失效
                    s = HttpKit.get(url);
                    LAST_TOKEN_TIME = DateKit.getAfterMin(110);//更新token
                }else {
                    return WX_TOKEN;
                }
            }
        }
        Map parse = JsonKit.parse(s, Map.class);
        Object access_token = parse.get("access_token");
        if(access_token != null){
            WX_TOKEN = access_token.toString();
        }
        return WX_TOKEN;
    }

    public static String getJsTicket(String accessToken){
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
        String s = "";
        String res = "";
        if(StringKit.isBlank(JSAPI)){
            s = HttpKit.get(url);
            LAST_JSAPI_TIME = DateKit.getAfterMin(110);//更新token
        }else {
            if(LAST_JSAPI_TIME == null ){
                s = HttpKit.get(url);
                LAST_JSAPI_TIME = DateKit.getAfterMin(110);//更新token
            }else {
                if(new Date().after(LAST_JSAPI_TIME)){//如果token失效
                    s = HttpKit.get(url);
                    LAST_JSAPI_TIME = DateKit.getAfterMin(110);//更新token
                }else {
                    return JSAPI;
                }
            }
        }
        Map parse = JsonKit.parse(s, Map.class);

        if(parse.get("errcode").toString().equals("0")){
            res = parse.get("ticket").toString();
            JSAPI = res;
        }
        return res;
    }

    public static Map getShareSign(String url){
        String accessToken = getAccessToken();
        String ticket = getJsTicket(accessToken);
        String timestamp = sign.create_timestamp();
        Map<String, String> sign = com.ikkong.system.util.sign.sign(ticket, url,timestamp);
        return  sign;
    }

    public static Map getWxUserInfo(String openid){
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
        String s = HttpKit.get(url);
        Map parse = JsonKit.parse(s, Map.class);
        return parse;
    }

    public static String codeToOpenid(String code){
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx86f9f7be6024c5a0&secret=b6a6e9e38433cadfa300f626f304fbd9&code="+code+"&grant_type=authorization_code";
        String s = HttpKit.get(url);
        return s;

    }

    public static List stringToList(String str){
        List list = new ArrayList();
        if(StringKit.isNotBlank(str)){
            list = Arrays.asList(str.split(","));
        }
        return list;
    }

    public static String codeToOpenidString(String code){
        String json = codeToOpenid(code);
        Map parse = JsonKit.parse(json, Map.class);
        String openid = "";
        if(parse!=null){
            try {
                String s = parse.get("openid").toString();
                openid = s;
            }catch (Exception e){
                System.out.println(e);
            }
        }
        return openid;
    }

    //发送模板消息--订单状态改变
    public static String sendOrderMsg(String touser,String num,String msg){
        MallOrder order = Blade.create(MallOrder.class).findById(num);
        String value = "请到我的订单页面查看";
        if(order!=null){
            if(order.getStatus() <= 2){
                value = "取货地址："+order.getAddress();
            }else if(order.getStatus()==3){
                value = "订单已完成，感谢使用";
            }
            value = order.getAddress();
        }
        String templetText = "{" +
                "     \"touser\":\""+touser+"\", " +
                "     \"template_id\":\"hsL_cDu6Me_Nou_dyh5CWhDznyErDlnNwTyrHHm4c90\", " +
                "     \"data\":{ " +
                "             \"first\": { " +
                "                 \"value\":\""+"订单状态更新提醒"+"\"" +
                "             }, " +
                "             \"keyword1\": { " +
                "                 \"value\":\""+num+"\"" +
                "             }, " +
                "             \"keyword2\": { " +
                "                 \"value\":\""+msg+"\"" +
                "             }, " +
                "             \"remark\": { " +
                "                 \"value\":\""+value+"\"" +
                "             }"+
                "     } " +
                " }  ";
        String access_token = getAccessToken();
        String post = HttpKit.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token,templetText);
        return post;
    }

    //发送模板消息
    public static String sendWithTemplet(String touser){
        String templetText = "{" +
                "     \"touser\":\""+touser+"\", " +
                "     \"template_id\":\"AIjcxh2F_mc1UfgXzzipL7pPUuGo0uR5IftKj0BqUto\", " +
                "     \"data\":{ " +
                "             \"productType\": { " +
                "                 \"value\":\""+"productType"+"\"" +
                "             }, " +
                "             \"number\": { " +
                "                 \"value\":\""+"number"+"\"" +
                "             }, " +
                "             \"expDate\": { " +
                "                 \"value\":\""+"expDate"+"\"" +
                "             }, " +
                "             \"remark\": { " +
                "                 \"value\":\""+"remark"+"\"" +
                "             }, " +
                "             \"name\": { " +
                "                 \"value\":\""+"name"+"\"" +
                "             }" +
                "     } " +
                " }  ";
        String access_token = getAccessToken();
        String post = HttpKit.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token,templetText);
        return post;
    }


    public static String limit(int page, int rows) {
        String limit = "";
        int start = (page - 1) * rows;
        limit = " limit " + start + " , " + rows;
        return limit;
    }

    public static String queryWl(String no) {
        String host = "https://wuliu.market.alicloudapi.com";
        String path = "/kdi";
        String method = "GET";
        String appcode = "1c4cabc97b554ad6bb260b401b31ecd2";  // !!!替换填写自己的AppCode 在买家中心查看
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode); //格式为:Authorization:APPCODE 83359fd73fe11248385f570e3c139xxx
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("no", no);// !!! 请求参数
        //JDK 1.8示例代码请在这里下载：  http://code.fegine.com/Tools.zip
        String rn = "";
        try {
            String s = HttpKit.get(host + path, querys, headers);
            //System.out.println(response.toString());如不输出json, 请打开这行代码，打印调试头部状态码。
            //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
            //获取response的body
            System.out.println(s); //输出json
            rn = s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rn;
    }


    public static String keyToSql(List keys) {

        String sql = "";
        for (int i = 0; i < keys.size(); i++) {
            if (i == 0) {
                sql += " SELECT question,anwser,number FROM auto_boot WHERE keywords LIKE \"%" + keys.get(i) + "%\"";
            } else {
                sql += " UNION SELECT question,anwser,number FROM auto_boot WHERE keywords LIKE \"%" + keys.get(i) + "%\"";
            }
        }
        if (StringKit.isNotBlank(sql)) {
            sql += " ORDER BY number DESC";
        }
        return sql;
    }


    public static Map mapwhere(String where) throws UnsupportedEncodingException {
        List<String> strings = new ArrayList<>();
        if (StringKit.isNotBlank(where)) {
            where = URLDecoder.decode(where, "utf-8");
            where = where.replaceAll("\"", "");
            where = where.replaceAll("_2nd", "");
            where = where.replaceAll("_equal", "");
            where = where.replaceAll("or_", "");
            where = where.replaceAll("\'", "");
            where = where.replaceAll("\\{", "");
            where = where.replaceAll("\\}", "");
            where = where.replaceAll(",", ":");
            strings = Arrays.asList(where.split(":"));
        }
        Map mt = new HashMap();
        if (strings.size() == 2) {
            mt.put(strings.get(0), "%" + strings.get(1) + "%");
        } else if (strings.size() == 4) {
            mt.put(strings.get(0), "%" + strings.get(1) + "%");
            mt.put(strings.get(2), "%" + strings.get(3) + "%");
        } else if (strings.size() == 6) {
            mt.put(strings.get(0), "%" + strings.get(1) + "%");
            mt.put(strings.get(2), "%" + strings.get(3) + "%");
            mt.put(strings.get(4), "%" + strings.get(5) + "%");
        } else if (strings.size() == 8) {
            mt.put(strings.get(0), "%" + strings.get(1) + "%");
            mt.put(strings.get(2), "%" + strings.get(3) + "%");
            mt.put(strings.get(4), "%" + strings.get(5) + "%");
            mt.put(strings.get(6), "%" + strings.get(7) + "%");
        }
        return mt;
    }

    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            return null;
        }
    }

    public static Map<?, ?> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        return new org.apache.commons.beanutils.BeanMap(obj);
    }


    public static Object fenye(List maps, int page, int rows) {
        int start = (page - 1) * rows;
        double d = maps.size() * 1.00 / rows * 1.00;
        int end = start + rows;
        if (end > maps.size()) {
            end = maps.size();
        }
        List<Map> newmap = maps.subList(start, end);
        Map sss = new HashMap();
        sss.put("rows", newmap);
        sss.put("total", Math.ceil(d));
        sss.put("page", page);
        sss.put("records", maps.size());
        Object o = sss;
        return o;
    }

    public static Object fenye(List maps, int page, int rows, int size) {
        int start = (page - 1) * rows;

        double d = size / rows;
        int end = start + rows;
        if (end > size) {
            end = size;
        }
        Map sss = new HashMap();
        if (start >= size) {
            sss.put("rows", new ArrayList());
        } else {
            sss.put("rows", maps);
        }

        sss.put("total", Math.ceil(d));
        sss.put("page", page);
        sss.put("records", size);


        Object o = sss;
        return o;
    }


    public static void createFieldNameList(List<Map<String, Object>> fieldNameList, String index, String width, String textAlign, String onRenderEvent, boolean isHidden) {
        Map<String, Object> fieldNameMap = new HashMap<String, Object>();
        fieldNameMap.put("index", index);
        fieldNameMap.put("width", width);
        fieldNameMap.put("textAlign", textAlign);
        fieldNameMap.put("isHidden", isHidden);
        fieldNameMap.put("onRenderEvent", onRenderEvent);
        fieldNameMap.put("isSort", true);
        fieldNameList.add(fieldNameMap);
    }

    public static boolean ynadmin() {
        List<String> roleList = ShiroKit.getUser().getRoleList();
        boolean b = false;
        for (String ss : roleList) {
            if ("1".equals(ss)) {
                b = true;
                break;
            }
        }
        return b;
    }

    public static boolean ynsuper() {
        List<String> roleList = ShiroKit.getUser().getRoleList();
        boolean b = false;
        for (String ss : roleList) {
            if ("1".equals(ss)) {
                b = true;
                break;
            }
        }
        return b;
    }

    public static String quchong(String s) {

        String[] array = s.split(",");
        Set<String> set = new HashSet<>();
        for (int i = 0; i < array.length; i++) {
            set.add(array[i]);
        }
        String[] arrayResult = (String[]) set.toArray(new String[set.size()]);
        return Arrays.toString(arrayResult);
    }
}
